package cn.kgc.microservicecloudproviderdept8001.controller;

import cn.kgc.microservicecloudapi.pojo.BookCategory;
import cn.kgc.microservicecloudapi.pojo.ResultEntity;
import cn.kgc.microservicecloudproviderdept8001.service.CategoryService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("/provider/category")
@RestController
public class CategoryController {

    @Resource
    CategoryService categoryService;
    @Resource
    DiscoveryClient client;
    @RequestMapping("/discovery")
    public Object discovery(){
        List<String> services = client.getServices();
        System.out.println("*****************************"+services);

        List<ServiceInstance> instances = client.getInstances("MICROSERVICECLOUD-PROVIDER-DEPT");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getServiceId());
            System.out.println(instance.getHost());
            System.out.println(instance.getPort());
            System.out.println(instance.getUri());
        }
        return this.client;
    }

    @RequestMapping("/list")
    public ResultEntity<List<BookCategory>> list(){
        List<BookCategory> all = categoryService.getAll();
        BookCategory bookCategory = new BookCategory();
        bookCategory.setName("8001");
        all.add(bookCategory);
        return ResultEntity.successWithoutData(all);
    }

    @RequestMapping("/get/{id}")
    public ResultEntity<BookCategory> get(@PathVariable Integer id){
        BookCategory category = categoryService.getById(id);
        return ResultEntity.successWithoutData(category);
    }

    @RequestMapping("/update")
    public ResultEntity<String> update(@RequestBody BookCategory category){
        int i = categoryService.updateByPrimaryKey(category);
        if (i>0){
            return ResultEntity.successWithoutData();
        }else{
            return ResultEntity.failed("修改失败");
        }
    }

    @RequestMapping("/insert")
    public ResultEntity<String> insert(@RequestBody BookCategory category){
        int i = categoryService.insert(category);
        if (i>0){
            return ResultEntity.successWithoutData();
        }else{
            return ResultEntity.failed("添加失败");
        }
    }

    @RequestMapping("/delete/{id}")
    public ResultEntity<String> delete(@PathVariable Integer id){
        int i=categoryService.deleteByPrimaryKey(id);
        if (i>0){
            return ResultEntity.successWithoutData();
        }else{
            return ResultEntity.failed("删除失败");
        }
    }

}

